#include "applyfriendpage.h"
#include <QPainter>
#include <QRandomGenerator>
#include <QStyleOption>
#include "applyfrienditem.h"
#include "applyfriendlist.h"
#include "tcpmgr.h"
#include "ui_applyfriendpage.h"
#include "usermgr.h"
#include <memory>
ApplyFriendPage::ApplyFriendPage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ApplyFriendPage)
{
    ui->setupUi(this);
    // 好友列表 鼠标按下事件 展示搜索结果
    connect(ui->apply_friend_list,
            &ApplyFriendList::sig_showSearch,
            this,
            &ApplyFriendPage::sig_showSearch);
    // 同意对方好于申请，修改好友申请列表中申请状态
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_authRsp, this, &ApplyFriendPage::slot_authRsp);
    loadApplyList();
}

ApplyFriendPage::~ApplyFriendPage()
{
    delete ui;
}

void ApplyFriendPage::addNewApply(std::shared_ptr<ApplyInfo> apply)
{
    // 随机模拟
    if (apply->icon.isEmpty()) {
        apply->icon = GetRandomIcon();
    } else {
        apply->icon = apply->icon;
    }

    ApplyFriendItem *applyItem = new ApplyFriendItem(this);
    applyItem->setInfo(apply);
    QListWidgetItem *item = new QListWidgetItem();
    item->setSizeHint(applyItem->sizeHint());
    item->setFlags(item->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);

    ui->apply_friend_list->addItem(item);
    ui->apply_friend_list->setItemWidget(item, applyItem);

    if (apply->status == 0) {
        applyItem->setAcceptBtnState(false);
        // 有未认证好友
        _unauthItemd[apply->uid] = applyItem;
        emit sig_hasNewFriendApply(_unauthItemd.size() > 0);
    } else {
        applyItem->setAcceptBtnState(true);
    }

    // 同意好友申请
    connect(applyItem,
            &ApplyFriendItem::sig_authFriend,
            this,
            [this, applyItem](std::shared_ptr<ApplyInfo> applyInfo) {
                applyItem->setAcceptBtnState(true);
            });
}

bool ApplyFriendPage::hasUnAuthenFriend()
{
    return _unauthItemd.size() > 0;
}

void ApplyFriendPage::loadApplyList()
{
    auto applyList = UserMgr::GetInstance()->GetApplyList();
    if (applyList.empty()) {
        return;
    }
    foreach (auto apply, applyList) {
        addNewApply(apply);
    }
}

void ApplyFriendPage::slot_authRsp(std::shared_ptr<AuthRsp> authRsp)
{
    // 收到确认添加好友回包
    int uid = authRsp->uid;
    qDebug() << "好友uid: " << uid;
    auto find_iter = _unauthItemd.find(uid);
    if (find_iter == _unauthItemd.end()) {
        qDebug() << "未找到好友申请！\n";
        return;
    }
    // 设置按钮状态为已接受
    find_iter->second->setAcceptBtnState(true);
    _unauthItemd.erase(uid);
    emit sig_hasNewFriendApply(_unauthItemd.size() > 0);
}

void ApplyFriendPage::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p);
    return QWidget::paintEvent(event);
}
